"use client";

import useSWR from "swr";
import {useEffect} from "react";
import {useAuth} from "@/components/authProvider";

const fetcher = (...args) => fetch(...args).then(res => res.json());

// const fetcher = async url => {
//     const res = await fetch(url);
//     if (!res.ok) {
//         const error = new Error("An error occurred while fetching the data.");
//         error.info = await res.json();
//         error.status = res.status;
//         throw error;
//     }
//     return res.json();
// }

const WORKOUT_API_URL = "/api/workouts";


export default function Page() {
    const auth = useAuth();
    // 访问自定义的代理/workouts/workouts
    const {data, error, isLoading} = useSWR(WORKOUT_API_URL, fetcher);

    useEffect(() => {
        console.log("error: ", error)
        if (!auth.isAuthenticated) {
            // 未登录
            auth.loginRequiredRedirect()
        }
    }, [auth, error])

    // console.log(error?.status);
    if (isLoading) {
        return (
            <div>
                loading...
            </div>
        )
    }
    if (error) {
        return (
            <div>
                failed to load
            </div>
        )
    }

    return (
        <main className="max-w-md mx-auto py-5">
            {JSON.stringify(data)}
        </main>
    );
}
